371. 两整数之和
为保证权益,题目请参考 371. 两整数之和(From LeetCode).
解决方案1
CPP
C++
//
// Created by lenovo on 2020-09-30.
//
#include <iostream>
using namespace std;
class Solution {
public:
int getSum(int a, int b) {
unsigned ans = 0;
unsigned add = 0;
do {
ans = unsigned (a) ^ unsigned (b);
add = unsigned (a & b);
a = ans;
b = add << 1;
} while (add != 0);
return ans;
}
};
void runTest() {
Solution so;
cout << so.getSum(1, 1) << endl;
}
int main() {
runTest();
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Python
python
# 371. 两整数之和
# https://leetcode-cn.com/problems/sum-of-two-integers/
################################################################################
class Solution:
def getSum(self, a: int, b: int) -> int:
MASK1 = 4294967296 # 2^32
MASK2 = 2147483648 # 2^31
MASK3 = 2147483647 # 2^31-1
m = a
n = b
while n != 0:
t = ((m&n) << 1) % MASK1
m = (m^n) % MASK1
n = t
if m & MASK2: # 负数
return ~((m ^ MASK2) ^ MASK3)
else: # 正数
return m
################################################################################
if __name__ == "__main__":
solution = Solution()
print(-2 & 1)
print(-2 & 2)
print(-2 & 4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34